/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sqlserver;

import Database.Table;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Zen
 */
public class SocketReceiver extends Thread{
    
    private Socket client;
    private SocketListener listener;
    boolean run;
    /**
     * @return the clients
     */
    public Socket getClients() {
        return client;
    }

    /**
     * @param clients the clients to set
     */
    public void setClients(Socket clients) {
        this.client = clients;
    }
    
    public SocketReceiver(Socket value, SocketListener listen)
    {
        client=value;
        listener=listen;
        run=true;
    }

    @Override
    public void run(){
        while(run==true)
        {
            try{
                byte[] buffer = null;
                ObjectInputStream ois;
                ois = new ObjectInputStream(client.getInputStream());
                String temp=null;
                try {
                    buffer=(byte[])ois.readObject();
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(SocketReceiver.class.getName()).log(Level.SEVERE, null, ex);
                }
                //lấy câu truy vấn
                temp=new String(buffer);
                
                //xử lý
                Object kq=new Object();
                if(temp!=null)
                {
                    kq=listener.Excute(temp);
                }
                
                if(kq==null&&!kq.getClass().equals(Table.class))
                    kq="Không có câu truy vấn kiểu này";

                ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream()) ;            
                oos.writeObject(kq);
            }catch (IOException e) 
            {                
                listener.Remove(this);        
                listener.AlertDisconnect();
                run=false;
            }
        }
    }
    
    public void Dispose()
    {
        byte[] buffer = "EXIT".getBytes();
        ObjectOutputStream oos ;       
        try {
            oos = new ObjectOutputStream(client.getOutputStream());
            oos.writeObject(buffer);
        } catch (IOException ex) {
            Logger.getLogger(SocketReceiver.class.getName()).log(Level.SEVERE, null, ex);
        }
        run=false;
    }
    public String getClientName()
    {
        return client.getInetAddress().getHostName();
    }
}
